<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Log;
use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Authenticatable implements JWTSubject
{
    use HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'id','nickname','icon','openid','is_admin',
        'name','identity','address','mobile','invite','remark'
    ];

    public function sign()
    {
        return $this->hasMany(AppUserSign::class,'user_id');
    }

    public function invite_user()
    {
        return $this->belongsTo(User::class,'invite');
    }

    protected static function booted()
    {
        static::updated(function ($model){

            if ($model->isDirty('openid')){

                $coupon = Coupon::where('type',1)
                    ->where('start','<=',date('Y-m-d'))
                    ->where('end','>=',date('Y-m-d'))
                    ->get();

                collect($coupon)->each(function ($item) use ($model){

                    UserCoupon::create([
                        'user_id'   => $model->id,
                        'coupon_id' => $item->id,
                        'value'     => $item->value,
                        'deadline'  => date('Y-m-d',strtotime('+'.$item->expire.' day')),
                    ]);

                });
            }


        });

    }

    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    public function getJWTCustomClaims()
    {
        return ['role'=>'app'];
    }
}
